package com.qiaofang.applet.rest;

import com.google.common.collect.Lists;
import com.qiaofang.applet.common.dto.DataRequest;
import com.qiaofang.applet.common.dto.DataResponse;
import com.qiaofang.applet.common.dto.PageDataRequest;
import com.qiaofang.applet.common.exception.BusinessException;
import com.qiaofang.applet.common.util.PageUtil;
import com.qiaofang.applet.constants.BusinessConstants;
import com.qiaofang.applet.constants.UpDownFlagConstants;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.service.EmployeePropertyService;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.member.service.dto.EmployeePropertyQueryDto;
import com.qiaofang.applet.service.member.service.mapstruct.EmployeeMapper;
import com.qiaofang.applet.service.property.domain.EstateHouseType;
import com.qiaofang.applet.service.property.domain.FirsthandEstate;
import com.qiaofang.applet.service.property.service.FirsthandEstateService;
import com.qiaofang.applet.service.property.service.dto.*;
import com.qiaofang.applet.service.property.service.mapstruct.FirsthandEstateMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/web/firsthandEstate")
@Api(tags = "房源：新房模块")
public class FirsthandEstateController {

    @Autowired
    private FirsthandEstateService firsthandEstateService;

    @Autowired
    private FirsthandEstateMapper firsthandEstateMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmployeePropertyService employeePropertyService;

    @PostMapping("/searchFirsthandEstate")
    @ApiOperation(value = "查询新房列表", notes = "查询新房列表")
    public DataResponse<Page<FirsthandEstateListDto>> searchFirsthandEstate(@RequestBody @Valid PageDataRequest<FirsthandEstateQueryDto> request) {
        // 经纪人主页选房源查询-排除经纪人已选房源
        if (StringUtils.isNotBlank(request.getParam().getEmployeeUniqueUuid())) {
            EmployeePropertyQueryDto queryDto = new EmployeePropertyQueryDto();
            queryDto.setEmployeeUniqueUuid(request.getParam().getEmployeeUniqueUuid());
            queryDto.setPropertyType(BusinessConstants.FIRSTHAND_ESTATE.getValue());
            List<String> uuidList = employeePropertyService.findPropertyListByParams(queryDto);
            request.getParam().setNotEstateUniqueUuids(uuidList);
        }

        request.getParam().setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());

        Page<FirsthandEstate> firsthandEstatePage = firsthandEstateService.findAllByParams(request.getParam(), PageUtil.getPageable(request));

        Page<FirsthandEstateListDto> result = firsthandEstateMapper.convertDomainToListDto(firsthandEstatePage);

        return DataResponse.ok(result);
    }

    @PostMapping("/getFirsthandEstate")
    @ApiOperation(value = "新房详情", notes = "新房详情")
    public DataResponse<FirsthandEstateDetailDto> getFirsthandEstate(@RequestBody @Valid DataRequest<FirsthandEstateDetailQueryDto> request) {
        FirsthandEstateDetailDto result = null;

        FirsthandEstate firsthandEstate = firsthandEstateService.findByEstateUniqueUuid(request.getParam().getEstateUniqueUuid());

        if (firsthandEstate != null) {
            result = firsthandEstateMapper.domainToDetailDto(firsthandEstate);
            result.setEmployeeListDtos(employeeService.getEmployeeListDtoByFirsthandEstate(firsthandEstate));
            result.setPropertyTypeList(firsthandEstateMapper.splitString(firsthandEstate.getPropertyType()));
        }

        return DataResponse.ok(result);

    }

    @PostMapping("/searchYouLike")
    @ApiOperation(value = "猜你喜欢", notes = "猜你喜欢")
    public DataResponse<List<FirsthandEstateListDto>> searchYouLike(@RequestBody @Valid DataRequest<FirsthandEstateQueryDto> request) {
        if (StringUtils.isBlank(request.getParam().getCityCode())) {
            throw new BusinessException("请先选择城市");
        }

        request.getParam().setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());

        List<FirsthandEstate> firsthandEstateList = firsthandEstateService.findAllByParamsAndRand(request.getParam());

        List<FirsthandEstateListDto> result = firsthandEstateList.stream().map(firsthandEstateMapper::domainToListDto).collect(Collectors.toList());

        return DataResponse.ok(result);
    }

    @PostMapping("/searchHouseType")
    @ApiOperation(value = "查询新房户型列表", notes = "查询新房户型列表")
    public DataResponse<List<EstateHouseTypeListDto>> searchHouseType(@RequestBody @Valid DataRequest<UuidDto> request) {
        List<EstateHouseTypeListDto> result = new ArrayList<>();

        FirsthandEstate firsthandEstate = firsthandEstateService.findByEstateUniqueUuid(request.getParam().getUuid());

        if (firsthandEstate != null) {
            List<EstateHouseType> houseTypeList = firsthandEstate.getHouseTypeList();

            if (!CollectionUtils.isEmpty(houseTypeList)) {

                Map<String, List<EstateHouseType>> houseTypeMap = Optional.ofNullable(houseTypeList)
                        .orElseGet(Lists::newArrayList).stream().collect(Collectors.groupingBy(EstateHouseType::getBedroom));

                Optional.ofNullable(houseTypeMap).orElse(new HashMap<>()).forEach((k, v) -> {
                    EstateHouseTypeListDto listDto = new EstateHouseTypeListDto();
                    listDto.setTypeName(k);
                    listDto.setTypeNum(v.size());
                    List<EstateHouseTypeDetailDto> typeList = new ArrayList<>();

                    for (EstateHouseType estateHouseType : v) {
                        EstateHouseTypeDetailDto detailDto = new EstateHouseTypeDetailDto();
                        BeanUtils.copyProperties(estateHouseType, detailDto);
                        typeList.add(detailDto);
                    }

                    listDto.setTypeList(firsthandEstateService.dealEstateHouseTypeWaterMark(typeList));
                    result.add(listDto);
                });
            }
        }

        return DataResponse.ok(result);
    }


    @PostMapping("/getFirsthandEstateV1")
    @ApiOperation(value = "新房详情", notes = "新房详情")
    public DataResponse<FirsthandEstateDetailDto> getFirsthandEstateV1(@RequestBody @Valid DataRequest<FirsthandEstateDetailQueryDto> request) {
        FirsthandEstateDetailDto result = null;

        FirsthandEstate firsthandEstate = firsthandEstateService.findByEstateUniqueUuid(request.getParam().getEstateUniqueUuid());

        if (firsthandEstate != null) {
            result = firsthandEstateMapper.domainToDetailDto(firsthandEstate);
            result.setPropertyTypeList(firsthandEstateMapper.splitString(firsthandEstate.getPropertyType()));
        }
        return DataResponse.ok(result);
    }


    @PostMapping("/getFirsthandShowEmp")
    @ApiOperation(value = "获取新房经纪人", notes = "获取新房经纪人")
    public DataResponse<PropertyEmpDto> getFirsthandShowEmp(@RequestBody @Valid DataRequest<FirsthandEstateDetailQueryDto> request) {
        PropertyEmpDto result = new PropertyEmpDto();
        if (StringUtils.isNotBlank(request.getParam().getEmployeeUniqueUuid())) {
            Employee employee = employeeService.findByEmployeeUniqueUuid(request.getParam().getEmployeeUniqueUuid());
            result.setEmployeeListDto(employeeService.domainToListDto(employee));
            if (request.getParam().isShowEmpList()) {
                result.setEmployeeListDtos(employeeService.getEmployeeDtoByFirsthand(request.getParam().getEstateUniqueUuid()).getEmployeeListDtos());
            }
        }else {
            result = employeeService.getEmployeeDtoByFirsthand(request.getParam().getEstateUniqueUuid());
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/searchYouLikeForEstatePK")
    @ApiOperation(value = "猜你喜欢(新房数据PK用)", notes = "猜你喜欢(新房数据PK用)")
    public DataResponse<List<FirsthandEstateListDto>> searchYouLikeForEstatePK(@RequestBody @Valid PageDataRequest<FirstEstateGuessLikeForPKDto> request) {
        if (StringUtils.isBlank(request.getParam().getCityCode())) {
            throw new BusinessException("请先选择城市");
        }
        List<FirsthandEstate> firsthandEstateList = firsthandEstateService.findAllByParamsAndRandForEstatePK(request.getParam(), PageUtil.getPageable(request));
        List<FirsthandEstateListDto> result = firsthandEstateList.stream().map(firsthandEstateMapper::domainToListDto).collect(Collectors.toList());
        return DataResponse.ok(result);
    }

    @PostMapping("/comparedEstateData")
    @ApiOperation(value = "对比新房数据", notes = "对比新房数据")
    public DataResponse<List<FirsthandEstateComparedDetailDto>> comparedEstateData(@RequestBody @Valid DataRequest<ComparedEstateDto> request) {
        return DataResponse.ok(firsthandEstateService.comparedEstateData(request.getParam()));
    }

    @PostMapping("/getFirstEstateEmployeePhone")
    @ApiOperation(value = "新房固定展示位经纪人手机号", notes = "新房固定展示位经纪人手机号")
    public DataResponse<String> getFirstEstateEmployeePhone(@RequestBody @Valid DataRequest<UniqueUuidDto> request) {
        return DataResponse.ok(firsthandEstateService.getFirstEstateEmployeePhone(request.getParam().getUniqueUuid()));
    }

}


